<template>
  <PageWrapper contentFullHeight dense>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="primary" @click="handleSubmit" v-hasAnyPermission="['commit:111']">
          <!-- {{ t('common.saveText') }} -->
          审核并提交
        </a-button>
        <a-button
          preIcon="ant-design:download-outlined"
          type="primary"
          @click="handleBatchDownload"
        >
          {{ t('common.title.download') }}
        </a-button>
        <BasicUpload2
          :api="UploadImport"
          :maxSize="20"
          :maxNumber="1"
          :showPreviewButton="false"
          :accept="['xlsx']"
          :uploadParams="{ bizType: FileBizTypeEnum.BASE_FILE }"
          @change="handleChanges"
          v-hasAnyPermission="['taskInterimTarget:importRecruit']"
        />
        <a-button
          v-hasAnyPermission="['taskInterimTarget:expirationTime']"
          type="primary"
          @click="openModal2"
        >
          设置资料上传截止时间</a-button
        >
        <BasicUpload
          :api="uploadFile"
          :maxNumber="1"
          :maxSize="20"
          :showPreviewButton="false"
          :accept="['xlsx']"
          :uploadParams="{ bizType: FileBizTypeEnum.BASE_FILE }"
          @change="FirstUpload"
          v-if="nextopenes"
        />
        <a-button
          color="success"
          @click="oped"
          v-if="(importFirst = 'true') && ops && upLoadShow == '1'"
          >重新上传文件</a-button
        >
        <BasicUpload
          :api="uploadFile"
          :maxNumber="1"
          :maxSize="20"
          :showPreviewButton="false"
          :accept="['xlsx']"
          :uploadParams="{ bizType: FileBizTypeEnum.BASE_FILE, sign: 1 }"
          @change="FirstUpload"
          v-if="nextopen && upLoadShow == '1'"
        />
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'action' && record.targetScore">
          <div class="father-btn">
            <BasicUpload
              :maxSize="20"
              :maxNumber="10"
              @change="handleChange"
              :api="UploadPdf"
              class="my-5"
              :accept="['pdf']"
              :records="record.id"
              v-if="
                upLoadShow != '1' &&
                record.targetType != '30' &&
                !record.isExpiration &&
                record.state
              "
              v-hasAnyPermission="['taskInterim:materialOperation']"
            />
            <a-button
              v-if="
                upLoadShow != '1' &&
                record.targetType != '30' &&
                (record.isExpiration || !record.state)
              "
              type="default"
              :disabled="true"
              >上传时间截止</a-button
            >
            <TableAction
              class="search"
              v-if="record.targetType != '30'"
              :actions="[
                {
                  icon: 'ant-design:search-outlined',
                  tooltip: '预览',
                  onClick: handleView.bind(null, record),
                },
              ]"
            />
          </div>
        </template>
      </template>
    </BasicTable>
    <Modal @register="register2" />
    <EditModal @register="registerDrawer" @success="handleSuccess" :foundId="upLoadShow" />
  </PageWrapper>
</template>
<script lang="ts">
  import {
    defineComponent,
    ref,
    unref,
    onMounted,
    shallowRef,
    ComponentOptions,
    // computed,
    // reactive ,
  } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { PageWrapper } from '/@/components/Page';
  import { handleFetchParams } from '/@/utils/lamp/common';
  import { TenantStatusEnum } from '/@/enums/biz/tenant';
  import {
    uploadFile,
    AllList,
    IddownLoad,
    UploadPdf,
    NewUpload,
    checklmport,
    commitConfirm,
    UploadImport,
    uploadFiles,
  } from '/@/api/basic/import/index';
  import { UploadPdfResult } from '/@/api/basic/import/model/Index';
  import { searchFormSchema, Updatecolumns } from './tenant.data';
  import { useUserStore } from '/@/store/modules/user';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { RoleEnum } from '/@/enums/roleEnum';
  import { FileBizTypeEnum } from '/@/enums/commonEnum';
  import { useModal } from '/@/components/Modal';
  import { ActionEnum } from '/@/enums/commonEnum';
  import { useDrawer } from '/@/components/Drawer';
  import { downloadFile } from '/@/utils/lamp/common';
  import { useRoute } from 'vue-router';
  import EditModal from './Edit.vue';
  import BasicUpload from './Upload/src/BasicUpload.vue';
  import BasicUpload2 from './Upload/src/BasicUpload2.vue';
  import { dateUtil } from '/@/utils/dateUtil';
  import Modal from './Modal.vue';
  // import { useLocalStorage } from '@vueuse/core';
  export default defineComponent({
    name: '我的部门',
    components: {
      BasicTable,
      PageWrapper,
      TableAction,
      EditModal,
      BasicUpload,
      BasicUpload2,
      Modal,
    },
    emits: ['change', 'delete', 'preview-delete', 'update:value', 'info'],
    setup() {
      const UploadThis = {
        bizType: 'INTERIM_TARGET',
        bucket: 'interim-target',
        storageType: 'MIN_IO',
      };
      let importFirst = 'false';
      onMounted(async () => {
        try {
          const response = await checklmport(); // 调用接口获取数据
          importFirst = String(response);
          return importFirst;
          // data.value = response.data; // 将接口返回的数据赋值给 data
        } catch (error) {
          console.error('Error fetching data:', error);
        }
      });
      const currentModal = shallowRef<Nullable<ComponentOptions>>(null);
      const nextopen = ref(false);
      const nextopenes = ref(false);
      const { t } = useI18n();
      const userStore = useUserStore();
      const { createMessage, createConfirm } = useMessage();
      const showSearche: any = userStore.getTenantId;
      const upLoadShow = userStore.getTenantId;
      const tanchuang = ref(false);
      const [register2, { openModal: openModal2 }] = useModal();
      const arr = {
        otherId: userStore.getTenantId,
      };

      const dataList = ref([]);
      const chakan = ref(Boolean);
      const fileList = ref<UploadPdfResult[] | any[]>([]);
      const [registerTable, { reload, getSelectRowKeys, getDataSource }] = useTable({
        title: '中期目标考核材料详情',
        api: AllList,
        columns: Updatecolumns,
        dataSource: dataList,
        formConfig: {
          labelWidth: 120,
          schemas: searchFormSchema(),
          // baseColProps: { xs: 24, sm: 12, md: 12, lg: 12, xl: 8 },
          autoSubmitOnEnter: true,
          resetButtonOptions: {
            preIcon: 'ant-design:rest-outlined',
          },
          submitButtonOptions: {
            preIcon: 'ant-design:search-outlined',
          },
        },
        childrenColumnName: 'list',
        // titleHelpMessage: [
        //   '成为部门步骤：',
        //   '1. 新增部门',
        //   '2. 等待平台方管理员(lamp)审核',
        //   '3. 运营者登录【开发运营系统】-【部门管理】-【部门维护】，并审批通过',
        //   '4. 运营者初始化数据源',
        //   '5. 运营者绑定您的账号为部门管理员',
        //   '6. 运营者通知您重新登录系统',
        // ],
        clickToRowSelect: false,
        isTreeTable: true,
        // accordion: true, // 手风琴效果
        beforeFetch: handleFetchParams,
        // useSearchForm: showSearche == '1' ? true : false,
        useSearchForm: true,
        showTableSetting: true,
        bordered: true,
        rowKey: 'id',
        rowSelection: {
          type: 'checkbox',
        },
        actionColumn: {
          width: 180,
          title: `预览下载支撑材料`,
          dataIndex: 'action',
        },
      });
      const route = useRoute();
      let allRestult: any[] = [];
      async function getDataList() {
        const result = await AllList(arr);
        return result;
      }
      // 弹出编辑页面
      function handleView(record: Recordable, e: Event) {
        // 获取表格数据参数
        const vass = getDataSource();
        chakan.value = vass[0].list[0].state;
        e?.stopPropagation();
        openDrawer(true, {
          record,
          type: ActionEnum.VIEW,
          opednext: chakan.value,
        });
      }

      // 编辑页弹窗
      const [registerDrawer, { openDrawer }] = useDrawer();
      // 新增或编辑成功回调
      function handleSuccess() {
        reload();
      }
      // 下载
      let otherid = '';
      const downloadProgress = ref(0);
      const isDownloading = ref(false);
      async function batchDownload(vvs, otherid) {
        const response = await IddownLoad(vvs, otherid);
        downloadFile(response);
        createMessage.success(t('common.tips.downloadSuccess'));
      }
      function handleBatchDownload() {
        const ids = getSelectRowKeys();
        var ot = ['1', '2', '3'];
        const vvs = ids.filter((item) => !ot.includes(item));
        if (!ids || ids.length <= 0) {
          createMessage.warning(t('common.tips.pleaseSelectTheData'));
          return;
        }
        if (upLoadShow !== '1') {
          otherid = upLoadShow;
        } else {
          reload().then((data) => {
            otherid = data[0].list[0].tenantId;
          });
        }
        createConfirm({
          iconType: 'warning',
          content: '确定要批量下载吗？',
          onOk: async () => {
            await batchDownload(vvs, otherid);
            createMessage.success(`下载成功`);
            // }
          },
        });
      }
      function splitArrayIntoChunks<T>(arr: T[], chunkSize: number): T[][] {
        const result: T[][] = [];
        for (let i = 0; i < arr.length; i += chunkSize) {
          result.push(arr.slice(i, i + chunkSize));
        }
        return result;
      }
      // 上传Pdf
      async function taskInterimMaterial(fileIds) {
        const result = await NewUpload(fileIds);
        return result;
      }
      function handleChange(files: UploadPdfResult[], UploadId: String) {
        fileList.value = [...unref(fileList), ...(files || [])];
        const newUpload: string[] = [];
        for (var i = 0; i < files.length; i++) {
          const list = [files[i].id];
          const StringList = String(list);
          newUpload.push(StringList);
        }
        const arrs = {
          targetId: UploadId,
          fileIds: newUpload,
        };
        taskInterimMaterial(arrs);
        // JSON.stringify(params)
        return createMessage.warning(t('component.upload.sessuess'));
      }
      function FirstUpload() {
        // route.go();
        createMessage.success(`文件上传成功`);
      }
      function handleChanges() {
        // route.go();
        nextopen.value = false;
        createMessage.success(`文件上传成功`);
      }
      let ops = ref(true);
      function oped() {
        // nextopen.value = true;
        createConfirm({
          iconType: 'warning',
          content: '确定要重新上传吗？一旦开启重新上传，之前所做的所有操作将全部失效',
          onOk: async () => {
            nextopen.value = true;
            ops.value = false;
          },
        });
      }
      // 保存最终分数
      // 提交
      async function handleSubmit() {
        const otherId = getDataSource();
        await commitConfirm(otherId[0].list[0].tenantId);
        createMessage.success(`评分提交成功`);
        reload();
      }
      function handleUpload() {
        nextopenes.value = true;
      }
      function timeChange() {
        currentModal.value = Modal;
      }

      return {
        TenantStatusEnum,
        t,
        registerTable,
        handleView,
        getDataList,
        upLoadShow,
        tanchuang,
        FileBizTypeEnum,
        RoleEnum,
        register2,
        openModal2,
        UploadThis,
        handleSuccess,
        registerDrawer,
        handleBatchDownload,
        handleChange,
        UploadPdf,
        IddownLoad,
        allRestult,
        otherid,
        uploadFile,
        uploadFiles,
        handleChanges,
        checklmport,
        importFirst,
        oped,
        route,
        nextopen,
        nextopenes,
        ops,
        FirstUpload,
        handleSubmit,
        chakan,
        handleUpload,
        UploadImport,
        dateUtil,
        timeChange,
        currentModal,
        downloadProgress,
        isDownloading,
        // downloadPercentage,
      };
    },
  });
</script>
<style>
  .search {
    flex: 1;
  }

  .my-5 {
    flex: 1;
  }

  .father-btn {
    display: flex;
  }

  .foundSome {
    float: right;
  }
</style>
